Dim dcEmpId As New DataColumn("EmpId", GetType(Integer))
dcEmpId.AutoIncrement = True ' Make it autoincrement.
dcEmpId.AutoIncrementSeed = 1
dcEmpId.AllowDBNull = False ' Default is True.
dcEmpId.Unique = True
dtEmp.Columns.Add(dcEmpId) ' Add to Columns collection.
' Make it the primary key.
Dim pkCols() As DataColumn = {dcEmpId}
dtEmp.PrimaryKey = pkCols
' (You can also use a more concise form, as follows:)
dtEmp.PrimaryKey = New DataColumn() {dcEmpId}
' This is a foreign key, but we haven't created the other table yet.
dtEmp.Columns.Add("DeptId", GetType(Integer))
' Add the DataTable to the DataSet.
ds.Tables.Add(dtEmp)
' Show the result in the DataGrid.
DataGrid2.DataSource = dtEmp
' -- fill the Employees table
' Create a new row with same schema.
Dim dr As DataRow = dtEmp.NewRow()
' Set all the columns.
dr("FirstName") = "Joe"
dr("LastName") = "Doe"
dr("BirthDate") = #1/15/1955#
dr("HomeAddress") = "1234 A Street"
dr("City") = "Los Angeles"
dr("DeptId") = 1
' Add to the Rows collection.
dtEmp.Rows.Add(dr)
dr = dtEmp.NewRow()
' Set all the columns.
dr("FirstName") = "Ann"
dr("LastName") = "Doe"
dr("BirthDate") = #1/15/1955#
dr("HomeAddress") = "1234 A Street"
dr("City") = "Los Angeles"
dr("DeptId") = 1
dtEmp.Rows.InsertAt(dr, 0)
' Read a semicolon-delimited text file into a DataTable.
' IMPORTANT: this works only if you copy the Employees.Dat
' file from the main project's directory to the BIN subdirectory
' Open the file, read its contents.
Dim sr As New System.IO.StreamReader("employees.dat")
Dim fileText As String = sr.ReadToEnd
sr.Close()
' This regular expression defines a row of elements, and assigns a name
' to each group (that is, a field in the text row).
Dim re As New System.Text.RegularExpressions.Regex("""(?<fname>[^""]+)"";""(?<lname>[^""]+)"";(?<bdate>[^;]+);""(?<addr>[^""]+)"";""(?<city>[^""]+)""")
Dim ma As System.Text.RegularExpressions.Match
dtEmp.BeginLoadData()
For Each ma In re.Matches(fileText)
' A new line has been found, so add a row to the table.
' Create an array of values and add it in one operation
Dim values() As Object = {ma.Groups("fname").Value, ma.Groups("lname").Value, _